<?php

namespace app\company\controller;

use app\common\model\Driver as DriverModel;
use app\common\controller\CompanyController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="司机管理")
 */
class Driver extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->sort  = ['sort' => 'desc', 'id' => 'desc'];
        $this->model = new DriverModel();
    }

    /**
     * @NodeAnnotation (title="添加")
     */
    public function add(Request $request): Json
    {
        try {
            $this->checkPost();
            $post = $request->post();
            $rule = [
                    'name|司机名称'    => 'require',
                    'phone|司机手机号' => 'require|mobile',
            ];
            $this->validate($post, $rule);
            if (empty($post['password'])) $post['password'] = '123456';
            $post['password']   = password($post['password']);
            $post['company_id'] = $this->companyId;
            $this->model->transaction(function () use ($post)
            {
                $this->model->save($post);
            });
        } catch (\Exception $e) {
            return $this->error('保存失败'.$e->getMessage());
        }
        return $this->success('保存成功');
    }

    /**
     * @NodeAnnotation (title="编辑")
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在！');
        if (empty($post['password'])) $post['password'] = '123456';
        $post['password'] = password($post['password']);
        $this->sceneValidate($post, 'edit');
        try {
            $this->model->transaction(function () use ($post, $row)
            {
                $row->save($post);
            });
        } catch (\Exception $e) {
            return $this->error('编辑失败');
        }
        return $this->success('编辑成功');
    }

}